/**
 *  Crazy Table Tool
 *  License by CrazyYi.
 *  v1.0.0 20200112
 *  v1.1.0 20200212: 增加 日期格式转换
 *
 */
layui.define(['table', 'laytpl', 'jquery'], function (exports) {
    const MOD_NAME = 'crazyDate';
    const TIME_FORMAT = 'yyyy-MM-dd HH:mm:ss';
    const oneDay = 1000 * 60 * 60 * 24; // 一天 的 毫秒数
    const $ = layui.jquery

    // ------------------------------------------------
    // 方法
    // ------------------------------------------------

    const formatNumber = function (n) { //给在0-9的日期加上0
        n = n.toString();
        return n[1] ? n : '0' + n
    };

    // ------------------------------------------------
    // 外部调用
    // ------------------------------------------------

    /**
     *
     * @type {{
     *      date2TimeStamp: (function(*): number),
     *      formatWeek: (function(*=): string),
     *      getDateDiff: (function(*, *): number),
     *      formatDateStr: (function(*): string),
     *      getDateFromFmt: (function(*): Date),
     *      today: (function(): string),
     *      formatTime: (function(*): string),
     *      currDateTime: (function(): *),
     *      formatNumber: (function(*): string),
     *
     *      someDay: (function(*): string),
     *      timeStamp2Date: (function(*=): string),
     *      laterTime: (function(*=): string),
     *      isNullDate: (function(*=): boolean),
     *
     *      }}
     */
    const classIns = {
        /**
         * 获取输入日期和当前日期的【天数差】
         * @param date1: 要判断的日期
         * @param date2: 参考的日期，默认是今天
         * @returns {number}
         */
        getDateDiff: function (date1, date2) {
            let s1 = new Date(date1.replace(/-/g, "/"));
            let s2 = (date2) ? new Date(date2.replace(/-/g, "/")) : new Date(); //当前日期：2017-04-24
            let days_timestamp = s2.getTime() - s1.getTime();
            let days_offset = Math.round(days_timestamp / oneDay);
            return days_offset;
        },
        /**
         * 根据输入的字符串，输出日期格式（-）
         */
        /**
         * 根据输入的字符串，输出日期格式
         * @param dateStr
         * @returns {*|Date}
         */
        formatDateStr: function (dateStr) {
            dateStr = dateStr ? dateStr : new Date();
            let year = dateStr.substr(0, 4)
            let month = dateStr.substr(4, 2)
            let day = dateStr.substr(6, 2)
            return [year, month, day].map(formatNumber).join('-');
        },
        /**
         * 输入日期字符串和对应的日期格式，输出Date对象
         * @param dateStr
         * @param format
         * @returns {*|Date}
         */
        getDateFromFmt: function (dateStr, format) {
            return CrazyDate.getDate(dateStr, format)
        },

        /**
         * 时间格式转换：UNIX 时间戳（毫秒） => 普通日期格式（YYYY-MM-DD HH:mm:ss）
         * @param uTimestamp: 毫秒时间戳
         * @returns {string}
         */
        timeStamp2Date: function (uTimestamp) {
            if (!uTimestamp) {
                let d = new Date();
                uTimestamp = d.getTime();
            }
            //timestamp 是整数，否则要parseInt转换
            let time = new Date(parseInt(uTimestamp)); // timestamp 是 【毫秒】
            let y = time.getFullYear();
            let M = time.getMonth() + 1;
            let d = time.getDate();
            let H = time.getHours();
            let m = time.getMinutes();
            let s = time.getSeconds();
            return [y, M, d].map(formatNumber).join('-') + ' ' + [H, m, s].map(formatNumber).join(':')
        },

        /**
         * 时间格式转换：普通日期格式（YYYY-MM-DD HH:mm:ss）=> UNIX 时间戳（毫秒）
         * @param inputDate
         * @returns {number}
         */
        date2TimeStamp: function (inputDate) {
            let dateStr = "" + inputDate;
            let t = (Date.parse(dateStr.replace(/-/gi, "/")));
            !t && (t = 0);
            return t;
        },

        /**
         * 获取今天的日期，格式：YYYY-MM-DD
         * @returns {string}
         */
        today: function () {
            let currToday = this.currDateTime();
            return currToday.substr(0, 10);
        },
        /**
         * 获取今天的日期，格式：YYYY-MM-DD HH:mm:ss
         * @returns {*|string|number}
         */
        currDateTime: function () {
            return this.formatTime(new Date());
        },
        /**
         * 给在0-9的日期加上0
         * @param n
         * @returns {string}
         */
        formatNumber: function (n) {
            n = n.toString();
            return n[1] ? n : '0' + n
        },
        /**
         * 时间格式转换：系统日期格式 => 普通日期格式（YYYY-MM-DD HH:mm:ss）
         * @param date
         * @param format
         * @param empty
         * @returns {number|*|string|*}
         */
        formatTime: function (date, format, empty) {
            empty = empty || (format === 'int' ? '0' : '--'); // 如果是空时间格式，则返回'--' 或 '0'
            date = date || new Date();
            if (this.isNullDate(date)) { return empty } // 如果是空时间格式，则返回'--' 或 '0'
            format = format || TIME_FORMAT;
            if (format === 'int') { return Math.round(date.getTime() / 1000) } // 如果是int，则直接返回时间戳（s）
            return CrazyDate.format(date, format);
        },
        /**
         * 根据date，计算星期几
         * @param date
         * @returns {string}
         */
        formatWeek: function (date) {
            let str = '';
            if (!!date) {
                let day = date.getDay();
                switch (day) {
                    case 0:
                        str = '星期日';
                        break;
                    case 1:
                        str = '星期一';
                        break;
                    case 2:
                        str = '星期二';
                        break;
                    case 3:
                        str = '星期三';
                        break;
                    case 4:
                        str = '星期四';
                        break;
                    case 5:
                        str = '星期五';
                        break;
                    case 6:
                        str = '星期六';
                        break;
                }
            }
            return str;
        },
        /**
         * 获取 N 天 前/后 的日期
         * @param dayDiff
         * @returns {string}
         */
        someDay: function (dayDiff) {
            dayDiff = dayDiff ? dayDiff : 0;
            let diff_timestamp = dayDiff * oneDay;
            let diff = new Date((new Date()).getTime() + diff_timestamp);
            const y = diff.getFullYear();
            const m = diff.getMonth() + 1;
            const d = diff.getDate();

            return [y, m, d].map(this.formatNumber).join('-');
        },
        /**
         * 获取输入时间戳t的延迟n 天的时间戳(ms)
         * @param days
         * @param time
         * @returns {*}
         */
        laterTime: function (days, time) {
            let n = days || 0;
            let t = time || (new Date()).getTime();
            t = t.constructor === Date ? t.getTime() : t;
            let diff = n * oneDay;
            return t + diff;
        },
        /**
         * 判断当前输入的时间格式的值（时间戳或者时间格式）是否小于 UNIX时间起点（1970-01-01 08:00:00）
         * @param v
         * @returns {boolean}
         */
        isNullDate: function (v) {
            return (!v || (parseInt(v) <= 0) || ((new Date(v)).getTime() <= 0))
        },

    };

    /**
     * 将UNIX的系统日期，转变成 format 格式 v1.1
     * @param date
     * @param format
     * @returns {*}
     * @constructor
     */
    const CrazyDate = {
        date: undefined,
        fmts: {
            y: ['yyyy', 'y'], M: ['MM', 'M'], d: ['dd', 'd'],
            H: ['HH', 'H'], m: ['mm', 'm'], s: ['ss', 's']
        }, // 当前laydate 支持的时间格式
        format: function (date, format) {
            this.date = date;
            const fmts = this.fmts;

            let str = format;
            let othis = this;
            let vals = {y: '', M: '', d: '', H: '', m: '', s: ''};
            $.each(this.fmts, function (k, fmt) {
                $.each(fmt, function (j, f) {
                    if (format.indexOf(f) > -1) {
                        vals[k] = othis[f](); // 求得当前的值
                        str = str.replace(f, vals[k]); // 替换
                        return false;
                    }
                });
            });
            return str;
        },
        yyyy: function () {return this.date.getFullYear()},
        y: function () {return parseInt(this.date.getFullYear())},
        MM: function () {return formatNumber(this.date.getMonth() + 1)},
        M: function () {return this.date.getMonth() + 1},
        dd: function () {return formatNumber(this.date.getDate())},
        d: function () {return this.date.getDate()},
        HH: function () {return formatNumber(this.date.getHours())},
        H: function () {return this.date.getHours()},
        mm: function () {return formatNumber(this.date.getMinutes())},
        m: function () {return this.date.getMinutes()},
        ss: function () {return formatNumber(this.date.getSeconds())},
        s: function () {return this.date.getSeconds()},

        /**
         * 将输入的时间字符串，转变成Date对象
         * @param dateStr
         * @param format
         * @returns {Date}
         */
        getDate: function (dateStr, format) {
            let vals = {y: '', M: '', d: '', H: '', m: '', s: ''};
            $.each(this.fmts, function (k, fmt) {
                $.each(fmt, function (j, f) {
                    if (format.indexOf(f) > -1) {
                        let p = format.indexOf(f); // 在format 中的位置
                        let l = f.length; // 当前格式的长度
                        vals[k] = dateStr.substr(p, l); // 截取对应的字符串
                        return false;
                    }
                })
            });
            if (!vals.y) {vals.y = (new Date()).getFullYear()}
            if (!vals.M) {vals.M = (new Date()).getMonth() + 1}
            let date = new Date(vals.y, vals.M, vals.d, vals.H, vals.m, vals.s);
            return date;
        },
    };

    //输出接口
    exports(MOD_NAME, classIns);

});
